package com.eascs.demand.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.demand.entity.*;
import com.eascs.demand.service.DemandApplyCommentService;
import com.eascs.demand.service.DemandService;
import com.eascs.demand.service.OldOaService;
import com.eascs.demand.service.TicketMainApplyService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.EmployeeService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.vo.ModelResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class TicketRestDemandViewController extends BaseRestController{
	private static Logger log = LoggerFactory.getLogger(TicketRestDemandViewController.class);
	/*****************数字常量****************/
	public static final int O2O_SEQUENCE_LENGTH=5;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	SysOrgService sysOrgService;
	@Autowired
	DemandApplyCommentService demandApplyCommentService;
	@Reference
	EmployeeService employeeService;
	@Inject
	private OldOaService oldOaService;
	@Inject
	private DemandService demandService;
	@Reference
	private SysPermissionService sysPermissionService;
	@Autowired
	private BaseUserUtil userUtils;
	@Inject
	TicketMainApplyService ticketMainApplyService;
	@Reference
	private SequenceService sequenceService;
	
	@RequestMapping("/demand/updateUI")
	public HtmlRestResult updateUIApply(String demandid) {
		UserDemand demand = demandService.getUserDemandById(demandid);
		ViewContext.put("userDemand", demand);
		return HtmlRestResult.popHtmlFragment("/demand/getDemandEditHtml");
	}
	
	/**
	 * 
	 * 工作流审批中补充附件表单
	 * 
	 * @param demandNo
	 * @return
	 */
	@RequestMapping("/demand/upload")
	public HtmlRestResult upload(String demandNo) {
		UserDemand userDemand = demandService.getById(UserDemand.class, demandNo);
		ViewContext.put("datalistInfo", getDatalistInfo(userDemand.getBillCode()));
		ViewContext.put("userDemand", userDemand);
		return HtmlRestResult.popHtmlFragment("/demand/upload");
	}
	
	/**
	 * 附件列表
	 * @param demandNo
	 * @return
	 */
	public PaginationInfo getDatalistInfo(String demandNo){
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(demandNo);
		String titles[] = {"附件类型","文件名", "提交人", "提交时间","更新时间"};
		Button[] titleButtons = new Button[] {null,ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "/loanUser/loanudpate");
//		Button delbutton = ButtonHelper.createAjaxButton("删除", "/demand/del?demandid=");
//		AjaxConfirmButton[]  dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
//		delbutton.setShowButtonFilter(new ShowButtonFilter() {
//			@Override
//			public boolean filter(Object arg0) {
//				Object []param = (Object[]) arg0;
//				if(("N").equals(param[1])){
//					return true;
//				}
//				return false;
//			}d
//		});
		//bao.pan
//		Button[] detailButton = new Button[] { starbutton,exitbutton,delbutton };
		datalistInfo.setTitleButtons(titleButtons);
//		datalistInfo.setMoreButtons(dealButton);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		return datalistInfo;
	}
	
	@RequestMapping(value = "/demand/update")
	public BaseRestResult<String> updateApply(UserDemand userDemand) {
		//修改需求表相关制字段
		UserDemand demandUpdate = demandService.getUserDemandById(userDemand.getId());
		demandUpdate.setTitle(userDemand.getTitle());
		demandUpdate.setDemandUser(userDemand.getDemandUser());
		demandUpdate.setDemandUserid(userDemand.getDemandUserid());
		User user=employeeService.getUserByNo(userDemand.getDemandUserid());
		if (user!=null) {
			demandUpdate.setDepname(user.getNodenamecn());
			log.info("更新需求部门={}", user.getNodenamecn());
		}
		log.info("更新需求user={}", user);
		demandUpdate.setDemandType(userDemand.getDemandType());
		demandUpdate.setDueDate(userDemand.getDueDate());
		demandUpdate.setDemandText(userDemand.getDemandText());
		EntityUtil.initUpdateEntity(demandUpdate);
//		demandService.updateDemandApply(demandUpdate);
		
		
		//修改主表
		MainApply mainApply = ticketMainApplyService.findMainApplyByExpandId(userDemand.getId());
		ModelResult<ActOrgEntity> modelResult = sysOrgService.getUniquePlatformWithUser(userDemand.getDemandUserid());
		if (!modelResult.isSuccess()) {
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
		mainApply.setLtd(modelResult.getModel().getUnitNo());
//		mainApply.setLtd(demandService.getLtdByUserNo(userDemand.getDemandUserid()));
		mainApply.setOperatorNo(userDemand.getDemandUserid());
		mainApply.setOperatorName(userDemand.getDemandUser());
		mainApply.setUpdateDate(new Date());
		mainApply.setUpdator(userUtils.getUserName());
		mainApply.setUpdatorId(userUtils.getCreateOr());
		//demandService.updateMainApplyById(mainApply);
		demandService.updateAll(mainApply, demandUpdate);
		return BaseRestResult.refresh();
	}
	
	/**
	 * 申请人
	 * 
	 * @param 
	 * @return
	 */
	@RequestMapping(value = "/operator")
	public BaseRestResult<List<Object[]>> referrer(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		data = oldOaService.getOperatorList(o2oSearchCustemer.getName());
		return BaseRestResult.buildRestResult(data);
	}
	
	
	
	@RequestMapping(value = "/demand/referrer")
	public BaseRestResult<List<Object[]>> operator(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			ModelResult<List<Object[]>> da = sysPermissionService.getOperatorList(o2oSearchCustemer.getName());
			data = da.getModel();
		}
		return BaseRestResult.buildRestResult(data);
	}
	
	
	
	
	//增加需求
	@RequestMapping("/demand/insert")
	public BaseRestResult<String> addApply(UserDemand userDemand) {
			List<Object[]> data = new ArrayList<>();
			String workeara="system";
			data = oldOaService.getOperatorWorkeara(userDemand.getDemandUserid());
			if (data.size()>0) {
				 workeara = data.get(0)[0].toString();	
			}
			String  billCode = buildCode("PDR", workeara);
			userDemand.setBillCode(billCode);
			String uuid = UUID.randomUUID().toString(); 
			userDemand.setId(uuid);
			//插入创建者
			userDemand.setCreator(userUtils.getUserName());
			//插入创建者id
			userDemand.setCreatorId(userUtils.getCreateOr());
			//插入状态  未删除 N
			userDemand.setIslock("N");
			userDemand.setStatus(StatusContexts.O2O_NEW);
			//插入修改者
			userDemand.setUpdator(userUtils.getUserName());
			//插入修改者id
			userDemand.setUpdatorId(userUtils.getCreateOr());
			//插入创建时间
			userDemand.setCreateDate(new Date());
			//插入修改时间
			userDemand.setUpdateDate(new Date());
			User user=employeeService.getUserByNo(userDemand.getDemandUserid());
			if (user!=null) {
				userDemand.setDepname(user.getNodenamecn());
				log.info("需求部门={}", user.getNodenamecn());
			}
			log.info("需求user={}", user);
			//插入用用户需求表
//			demandService.insertDemand(userDemand);
			
			//插入流程表主表
			MainApply mainApply = new MainApply();
			//扩展id
			mainApply.setExpandId(uuid);
			//需求单据编号
			mainApply.setBillCode(billCode);
			ModelResult<ActOrgEntity> modelResult = sysOrgService.getUniquePlatformWithUser(userDemand.getDemandUserid());
			if (!modelResult.isSuccess()) {
				return BaseRestResult.warn(modelResult.getErrMsg());
			}
			mainApply.setLtd(modelResult.getModel().getUnitNo());
//			mainApply.setLtd(demandService.getLtdByUserNo(userDemand.getDemandUserid()));
			mainApply.setOperatorNo(userDemand.getDemandUserid());
			mainApply.setOperatorName(userDemand.getDemandUser());
			mainApply.setBillStatus(StatusContexts.O2O_NEW);
			mainApply.setCreator(userUtils.getUserName());
			mainApply.setCreatorId(userUtils.getCreateOr());
			mainApply.setCreateDate(new Date());
			mainApply.setUpdateDate(new Date());
			mainApply.setUpdator(userUtils.getUserName());
			mainApply.setUpdatorId(userUtils.getCreateOr());
			mainApply.setIslock("N");
//			demandService.insertMainApply(mainApply);
			demandService.insertAll(userDemand, mainApply);
			ViewContext.put("userDemand", userDemand);
			return BaseRestResult.redirect("/demand/viewDemand/" + uuid);
	}
	
	@RequestMapping("/demand/viewDemand")
	public BaseRestResult<String> viewDemandRec(String demandId) {
		return BaseRestResult.redirect("/demand/viewDemand/" + demandId);
	}
	
	//删除需求UI
	@RequestMapping("/demand/del")
	public BaseRestResult<String> delApply(String demandid) {
		UserDemand userDemand = demandService.getUserDemandById(demandid);
		MainApply mainApply = ticketMainApplyService.findMainApplyByExpandId(demandid);
		int i=demandService.delAll(mainApply, userDemand);
//		int i = demandService.updateDemandApply(userDemand);
//		int j = ticketMainApplyService.updateMainApplyByEntity(mainApply);
		if(i>0){
			return BaseRestResult.warn("删除成功").andRefresh();
		} else if(i==0){
			return BaseRestResult.warn("删除失败,没有找到数椐。");
		} else {
			return BaseRestResult.warn("删除严重异常，请联系系统管理员");
		}
	}
	
	/**
	 * 生成贷款编号
	 * 
	 * @param code
	 * @param type
	 * @return
	 */
	public String buildCode(String code, String type) {
		String bill = StringUtils.getFourBitYearMonth(new Date());
		String prefix = code + "-" + type + "-" + bill;
		String flag = sequenceService.getSeq(SequenceEntity.O2O_LOAN_NO, O2O_SEQUENCE_LENGTH, prefix);
		if (flag == null) {
			throw new RuntimeException();
		}
		return flag;
	}

	@RequestMapping(value = "/comment/saveComment")
	public BaseRestResult<String> saveTicketComment(UserDemandApplyComment comment) {
		User user = UserHolder.getUser();
		comment.setCreateDate(new Date());
		comment.setCreator(user.getCode());
		comment.setCreatorName(user.getCname());

		comment.setUpdateDate(new Date());
		comment.setUpdator(user.getCode());
		comment.setUpdatorName(user.getCname());

		this.demandApplyCommentService.insert(comment);
		return BaseRestResult.refresh();
	}

	@RequestMapping(value = "/comment/getCommentEditView")
	public HtmlRestResult getCommentEditView(UserDemandApplyComment getEditViewForm) {
		ViewContext.put("billCode", getEditViewForm.getBillCode());
		return HtmlRestResult.popHtmlFragment("demand/getCommentEditView");
	}

	@RequestMapping(value = "/comment/getAllCommentView")
	public HtmlRestResult getAllTicketCommentView(UserDemandApplyComment comment) {
		List<UserDemandApplyComment> commentList = demandApplyCommentService.getCommentViewListByTicketId(comment.getBillCode());
		ViewContext.put("commentList", commentList);
		return new HtmlRestResult("demand/getAllCommentView");
	}
}
